﻿using System;
using System.ComponentModel.Composition.Hosting;
using System.ServiceModel;
using System.Windows;
using Microsoft.Practices.Prism.Regions;
using YunBox2.Contracts;
using YunBox2.Contracts.Core;

namespace YunBox2.Client.Infrastructure
{
    public sealed class ClientContext : DomainObject
    {
        private static ClientContext current;
        private Guid _clientID = Guid.NewGuid();
        private CompanyProfile _company;
        private User _currentUser;
        private int _loginExceptionCount;

        private ClientContext()
        {
            PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == "IsLogon")
                {
                    var regionManager = PrismContainer.GetExportedValue<IRegionManager>();
                    IRegion topRegion = regionManager.Regions[ShellRegionNames.TopRegion];
                    IRegion mainContentRegion = regionManager.Regions[ShellRegionNames.MainContentRegion];
                    if (IsLogon)
                    {
                        LoginExceptionCount = 0;
                        if (topRegion != null)
                        {
                            object logoutMenuView = topRegion.GetView("LogoutMenu");
                            if (logoutMenuView != null)
                            {
                                topRegion.Remove(logoutMenuView);
                            }

                            object loginMenuView = topRegion.GetView("LogonMenu");
                            if (loginMenuView == null)
                            {
                                loginMenuView = PrismContainer.GetExportedValue<LogonMenu>("LogonMenu");
                                topRegion.Add(loginMenuView, "LogonMenu");
                            }
                            topRegion.Activate(loginMenuView);
                        }


                        if (mainContentRegion != null)
                        {
                            object loginView = mainContentRegion.GetView("LoginPage");
                            if (loginView != null)
                            {
                                mainContentRegion.Remove(loginView);
                            }
                            regionManager.RequestNavigate(ShellRegionNames.MainContentRegion, "HomePage");
                        }
                    }
                    else
                    {
                        LoginExceptionCount++;
                        if (topRegion != null)
                        {
                            object logonMenuView = topRegion.GetView("LogonMenu");
                            if (logonMenuView != null)
                            {
                                topRegion.Remove(logonMenuView);
                            }

                            object logoutMenuView = topRegion.GetView("LogoutMenu");
                            if (logoutMenuView == null)
                            {
                                logoutMenuView = PrismContainer.GetExportedValue<LogoutMenu>("LogoutMenu");
                                topRegion.Add(logoutMenuView, "LogoutMenu");
                            }
                            topRegion.Activate(logoutMenuView);
                        }


                        if (mainContentRegion != null)
                        {
                            foreach (object obj in mainContentRegion.Views)
                            {
                                mainContentRegion.Remove(obj);
                            }

                            regionManager.RequestNavigate(ShellRegionNames.MainContentRegion, "LoginPage");
                        }
                    }
                }
            };
        }

        public static ClientContext Current
        {
            get
            {
                return current ?? (current = new ClientContext());
            }
        }

        /// <summary>
        /// 用户登录资料,登录成功后,初始化为0
        /// </summary>
        public int LoginExceptionCount
        {
            get
            {
                return _loginExceptionCount;
            }
            set
            {
                if (_loginExceptionCount != value)
                {
                    _loginExceptionCount = value;
                    if (_loginExceptionCount >= 3)
                    {
                        Application.Current.MainWindow.Close();
                    }
                    RaisePropertyChanged("LoginExceptionCount");
                }
            }
        }

        public bool IsLogon
        {
            get
            {
                return _currentUser != null;
            }
        }

        public Guid ClientID
        {
            get
            {
                return _clientID;
            }
            set
            {
                _clientID = value;
            }
        }

        public User CurrentUser
        {
            get
            {
                return _currentUser;
            }
            set
            {
                if (_currentUser != value)
                {
                    _currentUser = value;
                    RaisePropertyChanged("CurrentUser", "IsLogon");
                }
            }
        }

        public CompanyProfile Company
        {
            get
            {
                if (_company == null)
                {
                    SystemService.CompanyProfileToGetProfile(ClientID);
                }
                return _company;
            }
            set
            {
                _company = value;
                RaisePropertyChanged("Company");
            }
        }

        #region WCF

        private IFoundationService _foundationService;
        private ISystemService _systemService;

        public ISystemService SystemService
        {
            get
            {
                if (_systemService == null)
                {
                    var channel = new ChannelFactory<ISystemService>("system");

                    _systemService = channel.CreateChannel();
                }
                return _systemService;
            }
        }

        public IFoundationService FoundationService
        {
            get
            {
                if (_foundationService == null)
                {
                    var channel = new ChannelFactory<IFoundationService>("foundation");
                    _foundationService = channel.CreateChannel();
               }
                return _foundationService;
            }
        }

        private MsgHeader CreateMsgHeader()
        {
            return new MsgHeader { SessionId = ClientID };
        }

        public OperationContextScope CreateOperationContextScope(IContextChannel contextChannel)
        {
            var contextScope = new OperationContextScope(contextChannel);
            var header = new MessageHeader<MsgHeader>(CreateMsgHeader());
            OperationContext.Current.OutgoingMessageHeaders.Add(header.GetUntypedHeader(MsgHeader.HeaderLocalName, MsgHeader.HeaderNamespace));
            return contextScope;
        }

        #endregion

        #region prism

        public CompositionContainer PrismContainer
        {
            get;
            set;
        }

        #endregion
    }
}